<template>
  <div v-if="dialogShow" v-loading="loading" :element-loading-text="loadingText" class="add-config">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="handleBack">配置任务管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ detailData.type === 'edit' ? '编辑产品配置单' : '新增产品配置单' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div style="float: right">
        <el-button size="mini" @click="handleBack">取消</el-button>
        <el-button type="primary" size="mini" @click="handleSave">确定</el-button>
      </div>
    </div>
    <el-form ref="rulesForm" :model="formData" :rules="formRules" label-width="140px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="产品配置单:" prop="configCode">
            <span>{{ formData.configCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务来源:" prop="source">
            <span>{{ formaterData(taskSourceList, formData.source) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品配置类型:" prop="proConfigType">
            <span>{{ formaterData(proConfigTypeList, formData.proConfigType) }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="来源图纸任务:" prop="picTaskCode">
            <span>{{ formData.picTaskCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="图纸名称:" prop="picTaskName">
            <span>{{ formData.picTaskName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            v-if="showProDetail"
            label="产品分类明细:"
            prop="classDetail"
            :rules="[{ required: formData.proConfigType === 'ACCESSORY', message: '请选择产品分类明细' }]"
          >
            <c-dict-select v-model="formData.classDetail" dict-type-code="CLASS_DETAIL" placeholder="产品分类明细" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            v-if="showSendType"
            label="发货方式:"
            prop="deliveryMethod"
            :rules="[{ required: formData.proConfigType === 'RESOURCES', message: '请选择发货方式' }]"
          >
            <c-dict-select v-model="formData.deliveryMethod" dict-type-code="DELIVERY_METHOD" placeholder="发货方式" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店建设项目号:" prop="constCode">
            <span>{{ formData.constCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属门店编码:" prop="shopCode">
            <span>{{ formData.shopCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属门店名称:" prop="shopName">
            <span>{{ formData.shopName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属办事处:" prop="officeName">
            <span>{{ formData.officeName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品配置人员:" prop="proConfiguratorName">
            <span>{{ formData.proConfiguratorName }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="detailData.type === 'edit'" :span="8">
          <el-form-item label="创建时间:" prop="createTime">
            <span>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="detailData.type === 'edit'" :span="8">
          <el-form-item label="创建人:" prop="createBy">
            <span>{{ formData.createBy }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="detailData.type === 'edit'" :span="8">
          <el-form-item label="修改人:" prop="lastUpdateBy">
            <span>{{ formData.lastUpdateBy }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="detailData.type === 'edit'" :span="8">
          <el-form-item label="修改时间:" prop="lastUpdateTime">
            <span>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <c-section title="关联图纸信息">
      <RelevanceDrawing v-if="showPicDlg" ref="relevanceDrawing" :visible.sync="showPicDlg" :detail-data="activedData" @success="getPicTableData" />
      <div class="btn-container">
        <el-button type="primary" @click="choicePicTask">关联图纸</el-button>
        <el-button type="primary" @click="delTableData">删行</el-button>
      </div>
      <c-table-box :data="tableData" checkbox :table-config="tableConfig" @selection-change="selectionChange" />
    </c-section>
    <div style="margin-bottom: 20px">
      <c-section v-if="formData.proConfigType === 'FINISHED'" title="出图品类及数量">
        <c-table-box ref="outpicCategory" :table-max-height="200" :data="outpicCategoryData" no-request :table-config="tableConfigNum" />
      <!-- <div class="btn-container">
        <el-button type="primary">确认</el-button>
        <el-button type="primary">取消</el-button>
      </div> -->
      </c-section>
    </div>
  </div>
</template>
<script>
import RelevanceDrawing from './components/relevanceDrawing'
import { getProOutpicCategory, submitConfigTable, getProConfigEditData, getTaskDetail } from '@/api/proConfig'
import { getDictByPatchType } from '@/api/dataDict'
// import { queryAreaData } from '@/api/storeConstruction'
import { getAreaData } from '../components/index'
export default {
  name: 'AddConfig',
  components: {
    RelevanceDrawing
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      loadingText: '',
      picTypeList: [],
      designRangeList: [],
      decorationTypeList: [],
      designSpaceList: [],
      designBizTypeList: [],
      activedData: {},
      showPicDlg: false,
      showProDetail: false,
      showSendType: false,
      taskSourceList: [],
      proConfigTypeList: [],
      picIds: [],
      formData: {
        classDetail: '',
        deliveryMethod: ''
      },
      formRules: {

      },
      tableData: [],
      tableSelected: [],
      outpicCategoryData: [],
      tableConfig: {
        // interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopDesignPicture/page`,
        hideFuncBar: true,
        setting: [
          {
            prop: 'picTaskCode',
            label: '图纸编码',
            minWidth: 100
          },
          {
            prop: 'picType',
            label: '图纸类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_TYPE'
            },
            minWidth: 100
          },
          {
            prop: 'designRange',
            label: '设计范围',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designRange) {
                return
              }
              let list = []
              if (typeof (row.designRange) === 'string') {
                list = row.designRange.split(',')
              } else {
                list = row.designRange
              }
              const arr = []
              this.designRangeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'decorationType',
            label: '装修形式',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.decorationType) {
                return
              }
              let list = []
              if (typeof (row.decorationType) === 'string') {
                list = row.decorationType.split(',')
              } else {
                list = row.decorationType
              }
              const arr = []
              this.decorationTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designSpace',
            label: '设计区域',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designSpace) {
                return
              }
              let list = []
              if (typeof (row.designSpace) === 'string') {
                list = row.designSpace.split(',')
              } else {
                list = row.designSpace
              }
              const arr = []
              this.areaList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designBizType',
            label: '设计业务类型',
            minWidth: 140,
            render: (creat, row) => {
              if (!row.designBizType) {
                return
              }
              let list = []
              if (typeof (row.designBizType) === 'string') {
                list = row.designBizType.split(',')
              } else {
                list = row.designBizType
              }
              const arr = []
              this.designBizTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'picTotalArea',
            label: '设计总面积',
            minWidth: 120
          },
          // {
          //   prop: 'finishedProductAreaSummary',
          //   label: '成品业务面积汇总',
          //   minWidth: 100
          // },
          {
            prop: 'softwareSumArea',
            label: '软体区面积',
            minWidth: 120
          },
          {
            prop: 'suiteSumArea',
            label: '套房区面积',
            minWidth: 120
          },
          {
            prop: 'haveEAndC',
            label: '是否含成融定',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: 140
          },
          {
            prop: 'eandCArea',
            label: '成融定面积',
            minWidth: 120
          },
          {
            prop: 'newBusinessAreaSummary',
            label: '新业务面积汇总',
            minWidth: 100
          },
          {
            prop: 'expectEndTime',
            label: '预计设计完成时间',
            minWidth: 140
          },
          {
            prop: 'designUnitName',
            label: '设计单位',
            minWidth: 100
          },
          {
            prop: 'designerName',
            label: '设计师',
            minWidth: 100
          },
          {
            prop: 'schedule',
            label: '图纸进度',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_SCHEDULE'
            },
            minWidth: 100
          },
          {
            prop: 'state',
            label: '图纸状态',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_STATE'
            },
            minWidth: 100
          }
        ]
      },
      tableConfigNum: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/designOutpicCategoryNumber/page`,
        hideFuncBar: true,
        setting: [
          {
            prop: 'areaName',
            label: '所属区域'
          },
          {
            prop: 'spaceName',
            label: '所属空间'
          },
          {
            prop: 'spaceTotalArea',
            label: '空间面积'
          },
          {
            prop: 'seriesName',
            label: '系列名称'
          },
          {
            prop: 'styleName',
            label: '所属专区'
          },
          {
            prop: 'categoryNames',
            label: '包含品类'
          },
          {
            prop: 'categoryNumber',
            label: '出图品类数量'
          }
        ]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  async created() {
    await this.getDictByPatchTypeAll(['PRODUCT_CONFIG_TASK_SOURCE', 'PRO_CONFIG_TYPE', 'DECORATION_RANGE',
      'DECORATION_FORM', 'BELONG_REGION', 'BIZ_TYPE']).then(res => {
      this.taskSourceList = res.PRODUCT_CONFIG_TASK_SOURCE
      this.proConfigTypeList = res.PRO_CONFIG_TYPE
      this.designRangeList = res.DECORATION_RANGE // 设计范围
      this.decorationTypeList = res.DECORATION_FORM // 装修形式
      this.designSpaceList = res.BELONG_REGION // 设计区域
      this.designBizTypeList = res.BIZ_TYPE // 设计业务类型
    })
    this.areaList = await getAreaData()
    // this.formData = this.detailData.formData
    await getTaskDetail(this.detailData.formData.id).then(res => {
      if (res.success) {
        this.formData = res.data
        this.tableData = res.data.designPictureDtos || []
      }
    })
    // this.tableData = this.detailData.formData.designPictureDtos || []
    if (this.detailData.type === 'edit') {
      this.loading = true
      this.loadingText = '加载中'
      await getProConfigEditData(this.detailData.picData.id).then(res => {
        if (res.success && res.data) {
          this.formData = res.data
          this.tableData = res.data.designPictureDtos
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
      // this.formData = this.detailData.formData
      // this.tableData = this.detailData.picData
      // this.getOutpicCategory(this.tableData)
    }
    if (this.formData.proConfigType === 'FINISHED') {
      this.getOutpicCategory(this.tableData)
    }
    this.$nextTick(() => {
      if (this.formData.proConfigType === 'RESOURCES') {
        this.showSendType = true
        // const rules = [{ required: true, message: '请选择送货方式' }]
        // this.$set(this.formRules, 'deliveryMethod', rules)
        // this.$set(this.formRules, 'classDetail', undefined)
        // this.$refs.rulesForm.clearValidate()
      } else if (this.formData.proConfigType === 'ACCESSORY') {
        this.showProDetail = true
        // const rules = [{ required: true, message: '请选择产品分类明细' }]
        // this.$set(this.formRules, 'classDetail', rules)
        // this.$set(this.formRules, 'deliveryMethod', undefined)
      }
      this.$refs.rulesForm.clearValidate()
    })
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    selectionChange(rows) {
      this.tableSelected = rows
    },
    // async getAreaData() {
    //   const dataForm = new FormData()
    //   dataForm.append('pageFlag', false)
    //   return await queryAreaData(dataForm).then(res => {
    //     if (res.success && res.data) {
    //       const arr = res.data.records
    //       const areaList = arr.map(item => {
    //         const obj = { dictCode: item.areaCode, dictName: item.areaName }
    //         return obj
    //       })
    //       return areaList
    //     }
    //   })
    // },
    // 关联图纸
    choicePicTask() {
      this.activedData = this.formData
      this.showPicDlg = true
    },
    // 接收选择的关联图纸
    getPicTableData(data) {
      if (!this.tableData.length) {
        this.tableData = [...data]
        this.getOutpicCategory(this.tableData)
      } else {
        const arr1 = []
        const arr2 = []
        data.forEach(item => {
          const flag = this.tableData.some(v => v.picTaskCode === item.picTaskCode)
          if (flag) {
            arr1.push(item)
          } else {
            arr2.push(item)
          }
        })
        if (arr1.length > 0) {
          const msgArr = arr1.map(item => item.picTaskCode)
          this.$message.warning(`编码为${msgArr.toString()}的图纸已存在`)
        }
        this.tableData = [...this.tableData, ...arr2]
        if (!arr2.length) return
        this.getOutpicCategory(this.tableData)
      }
    },
    // 删行
    delTableData() {
      if (!this.tableSelected.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      const list = ['RESOURCES', 'ACCESSORY']
      if (!list.includes(this.formData.proConfigType)) {
        const arr = this.tableSelected.filter(item => item.picTaskCode === this.formData.picTaskCode)
        if (arr.length) {
          this.$message.warning('不可删除来源图纸项，请重新选择')
          return
        }
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = this.tableData.filter(item => {
          const index = this.tableSelected.findIndex(row => row.picTaskCode === item.picTaskCode)
          return index === -1
        })
        this.tableData = JSON.parse(JSON.stringify(arr))
        this.getOutpicCategory(this.tableData)
      })
    },
    // 获取出图品类及数量
    getOutpicCategory(arr) {
      if (!arr.length) return
      const picTaskCodes = arr.map(item => item.picTaskCode)
      // const picTaskStr = '[' + picTaskCodes.join(',') + ']'
      // const filter = [{ 'id': 'picTaskCode', 'property': 'picTaskCode', 'operator': 'in', 'value': picTaskStr }]
      // const dataForm = new FormData()
      // dataForm.append('filtersRaw', JSON.stringify(filter))
      getProOutpicCategory(picTaskCodes).then(res => {
        if (res.success && res.data && res.data.records) {
          this.outpicCategoryData = res.data.records
          this.outpicCategoryData.forEach(item => {
            item.outpicCategoryNumberId = item.id
          })
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    // 取消新增
    handleBack() {
      this.dialogShow = false
      this.formData = {}
      this.$emit('goBack')
    },
    // 新增
    handleSave() {
      this.$refs.rulesForm.validate((valid) => {
        if (valid) {
          if (!this.tableData.length) {
            this.$message.warning('请关联图纸')
            return
          }
          // return
          this.formData.picIds = this.tableData.map(item => item.id)
          // this.formData.picIds = this.picIds
          // return
          this.formData.productConfigDetailDtos = this.outpicCategoryData
          this.loading = true
          this.loadingText = '系统处理中'
          submitConfigTable(this.formData).then(res => {
            if (res.success) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.handleBack()
              const isNew = !this.formData.id // 是否新增数据 true (新增则刷新列表到第一页)/ false (非新增则刷新当前页)
              this.$emit('success', isNew)
            }
            this.loading = false
            this.loadingText = ''
          }).catch(() => {
            this.loading = false
            this.loadingText = ''
          })
        }
      })
    }
  }
}
</script>
